from datetime import datetime
import random

class CanteenFood:
    """食堂菜品类"""
    def __init__(self, food_id, name, price, category):
        self.food_id = food_id  # 菜品ID
        self.name = name        # 菜品名称
        self.price = price      # 菜品价格
        self.category = category# 菜品分类

class CanteenOrderSystem:
    """食堂点餐支付系统"""
    def __init__(self):
        # 初始化菜单（模拟食堂菜品数据）
        self.menu = [
            CanteenFood(1, "宫保鸡丁", 15.8, "荤菜"),
            CanteenFood(2, "鱼香肉丝", 14.5, "荤菜"),
            CanteenFood(3, "清炒时蔬", 8.9, "素菜"),
            CanteenFood(4, "番茄炒蛋", 10.0, "荤素搭配"),
            CanteenFood(5, "麻婆豆腐", 9.5, "素菜"),
            CanteenFood(6, "红烧肉", 22.8, "荤菜"),
            CanteenFood(7, "扬州炒饭", 12.0, "主食"),
            CanteenFood(8, "小米粥", 3.0, "粥品"),
            CanteenFood(9, "可乐", 4.0, "饮品"),
            CanteenFood(10, "矿泉水", 2.0, "饮品")
        ]
        self.cart = []  # 购物车：存储选中的菜品及数量
        self.order_id = ""  # 订单号

    def show_menu(self):
        """展示食堂菜单"""
        print("\n" + "="*40)
        print("🍽️  食堂菜单")
        print("="*40)
        # 按分类分组展示
        categories = {}
        for food in self.menu:
            if food.category not in categories:
                categories[food.category] = []
            categories[food.category].append(food)
        
        for category, foods in categories.items():
            print(f"\n【{category}】")
            print(f"{'ID':<4} {'菜品名称':<10} {'价格(元)':<8}")
            print("-"*25)
            for food in foods:
                print(f"{food.food_id:<4} {food.name:<10} {food.price:<8.1f}")
        print("="*40 + "\n")

    def add_to_cart(self):
        """添加菜品到购物车"""
        while True:
            try:
                food_id = input("请输入要添加的菜品ID（输入0结束选餐）：")
                if food_id == "0":
                    break
                
                food_id = int(food_id)
                # 查找对应的菜品
                selected_food = None
                for food in self.menu:
                    if food.food_id == food_id:
                        selected_food = food
                        break
                
                if not selected_food:
                    print("❌ 无效的菜品ID，请重新输入！")
                    continue
                
                # 输入购买数量
                quantity = int(input(f"请输入{selected_food.name}的购买数量："))
                if quantity <= 0:
                    print("❌ 数量必须大于0，请重新输入！")
                    continue
                
                # 检查购物车中是否已有该菜品，有则更新数量
                in_cart = False
                for item in self.cart:
                    if item["food"].food_id == food_id:
                        item["quantity"] += quantity
                        in_cart = True
                        break
                
                if not in_cart:
                    self.cart.append({
                        "food": selected_food,
                        "quantity": quantity
                    })
                
                print(f"✅ {selected_food.name} × {quantity} 已添加到购物车！")
            
            except ValueError:
                print("❌ 输入格式错误，请输入数字！")

    def show_cart(self):
        """展示购物车"""
        if not self.cart:
            print("\n🛒 购物车为空！")
            return
        
        print("\n" + "="*40)
        print("🛒 购物车")
        print("="*40)
        print(f"{'序号':<4} {'菜品名称':<10} {'单价(元)':<8} {'数量':<4} {'小计(元)':<8}")
        print("-"*40)
        
        total_amount = 0
        for idx, item in enumerate(self.cart, 1):
            food = item["food"]
            quantity = item["quantity"]
            subtotal = food.price * quantity
            total_amount += subtotal
            print(f"{idx:<4} {food.name:<10} {food.price:<8.1f} {quantity:<4} {subtotal:<8.1f}")
        
        print("-"*40)
        print(f"{'合计金额':<30} {total_amount:.1f} 元")
        print("="*40 + "\n")
        return total_amount

    def remove_from_cart(self):
        """从购物车移除菜品"""
        if not self.cart:
            print("❌ 购物车为空，无需移除！")
            return
        
        self.show_cart()
        try:
            idx = int(input("请输入要移除的菜品序号（输入0取消）："))
            if idx == 0:
                return
            
            if 1 <= idx <= len(self.cart):
                removed_item = self.cart.pop(idx-1)
                print(f"✅ 已移除 {removed_item['food'].name} × {removed_item['quantity']}")
            else:
                print("❌ 无效的序号！")
        
        except ValueError:
            print("❌ 输入格式错误，请输入数字！")

    def generate_order_id(self):
        """生成唯一订单号（日期+随机数）"""
        date_str = datetime.now().strftime("%Y%m%d%H%M%S")
        random_str = str(random.randint(1000, 9999))
        self.order_id = f"CANTEEN{date_str}{random_str}"

    def pay_order(self, total_amount):
        """支付订单"""
        if total_amount <= 0:
            print("❌ 订单金额异常，无法支付！")
            return False
        
        print("\n" + "="*40)
        print("💳 支付结算")
        print("="*40)
        print(f"订单金额：{total_amount:.1f} 元")
        print("\n支持的支付方式：")
        print("1. 微信支付")
        print("2. 支付宝支付")
        print("3. 校园卡支付")
        
        while True:
            try:
                pay_choice = int(input("\n请选择支付方式（1-3）："))
                if pay_choice not in [1,2,3]:
                    print("❌ 无效的选择，请输入1-3！")
                    continue
                
                # 模拟支付过程
                print("\n正在处理支付...")
                import time
                time.sleep(1.5)  # 模拟支付延迟
                
                # 模拟支付成功（95%成功率）
                if random.random() < 0.95:
                    self.generate_order_id()
                    pay_method = ["微信支付", "支付宝支付", "校园卡支付"][pay_choice-1]
                    print(f"\n🎉 支付成功！")
                    print(f"订单号：{self.order_id}")
                    print(f"支付方式：{pay_method}")
                    print(f"支付金额：{total_amount:.1f} 元")
                    print(f"支付时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
                    print(f"📢 提示：请凭订单号到取餐口取餐，祝您用餐愉快！")
                    return True
                else:
                    print("\n❌ 支付失败！请检查支付账户余额或网络连接，重试支付。")
                    retry = input("是否重新支付？（y/n）：").lower()
                    if retry != "y":
                        return False
            
            except ValueError:
                print("❌ 输入格式错误，请输入数字！")

    def run(self):
        """运行点餐系统"""
        print("="*50)
        print("🍚 欢迎使用校园食堂点餐支付系统 🍚")
        print("="*50)
        
        while True:
            print("\n📋 功能菜单：")
            print("1. 查看菜单")
            print("2. 添加菜品到购物车")
            print("3. 查看购物车")
            print("4. 移除购物车菜品")
            print("5. 结算支付")
            print("0. 退出系统")
            
            try:
                choice = int(input("\n请选择功能（0-5）："))
                
                if choice == 0:
                    print("\n👋 感谢使用，再见！")
                    break
                
                elif choice == 1:
                    self.show_menu()
                
                elif choice == 2:
                    self.add_to_cart()
                
                elif choice == 3:
                    self.show_cart()
                
                elif choice == 4:
                    self.remove_from_cart()
                
                elif choice == 5:
                    total = self.show_cart()
                    if total > 0:
                        confirm = input("是否确认支付？（y/n）：").lower()
                        if confirm == "y":
                            if self.pay_order(total):
                                # 支付成功后清空购物车，结束本次点餐
                                self.cart = []
                                print("\n" + "="*50)
                                print("🎊 本次点餐流程结束！")
                                print("="*50)
                    else:
                        print("❌ 购物车为空，无法结算！")
                
                else:
                    print("❌ 无效的选择，请输入0-5之间的数字！")
            
            except ValueError:
                print("❌ 输入格式错误，请输入数字！")

if __name__ == "__main__":
    # 启动系统
    system = CanteenOrderSystem()
    system.run()